04 - Arrays and text

04 - Arrays and text


🔨 🔥 Assignment 🔥 🔨

Create a new project in the way explained in the first instruction.


Arrays

Arrays are series of elements of the same type placed aside in the memory. They compose one continuous block. An array has a name, which is an address of its first element plus information of types of its elements. Elements of an array can be accessed by use of array name and element index in square brackets []:

int arr[5] = {1, 2, 3, 4, 5};
for (int i = 0; i < 5; i++)
{
    std::cout << "arr[" << i << "] = " << arr[i] << std::endl;
}

ATTENTION Array’s elements are numbered from 0, so the last element index is n-1, where n is a size of an array.

To define an array a constant value denoting a number of elements has to be provided:

int ar1[4];     // Good

const int cnum = 4;
int ar3[cnum];  // Good

int num = 4;
int ar3[num];   // Not part of C++ standard, might not work in some compilers

Arrays, like fundamental types are not initialized, by default. At definition, arrays can be initialized with use of {}, even if their size was not provided:

int ar5[4] = {1, 2, 3, 4}; // ar5 = [ 1 2 3 4 ]
int ar6[4] = {1, 2};       // ar6 = [ 1 2 0 0 ]
int ar7[4] = {};           // ar7 = [ 0 0 0 0 ]
int ar8[] = {1, 2};        // ar8 = [ 1 2 ]
int ar9[2];                // ar9 = [ random1 random2 ]

After initialisation array elements can be accessed using square brackets []. Array elements can be accessed independently only, one by one, not in groups:

ar8[] = {5, 6}; // Error!!!
ar5[0] = 5;     // Good
ar5[4] = 4;     // Error!!! Memory corruption, ar5 has 4 elements from 0 to 3

std::cout << ar5[0] << std::endl; // Will print 5

🔨 🔥 Assignment 🔥 🔨

  1. Write a program which will ask the user for 5 int type values, store them in array of int and then display them. In both cases use a for loop.
  2. Modify the program so it displays sum and product of user provided values.

Additional information on arrays can be found here: http://www.cplusplus.com/doc/tutorial/arrays/

Text processing

In C text is stored as array of characters, containing values corresponding to ASCII code values of characters:

char arch[] = {'a', 'b', 'c'}; // array in decimal: [ 97 98 99 ]

Arrays of characters are treated in the same manner as other arrays. To make working with text more convenient, text in C is usually stored in NULL (0) terminated arrays, called C-strings or shorter strings. They are identical to standard character arrays, but require additional NULL (0) value at the end. Also their initialization is more convenient, using "":

char st1[] = {'a', 'b', 'c', '\0'}; // string: "abc" = [ 97 98 99 0]
char st2[] = "abc";                 // string: "abc" = [ 97 98 99 0]
char st3[4] = "a";                  // string: "a"     = [ 97  0  0 0]
char st4[] = st2 + st3;             // Error!!!

Quotation marks can be used only on initialization. After that, C-strings can be operated as other array types:

st1[] = {'a', 'b', 'c', '\0'}; // Error!!!
st1[] = "abc";                 // Error!!!
st1 = "abc"                    // Error!!!
st1[0] = "a";                  // Error!!!
st1[0] = 'a';                  // Good
st1[0] = 97;                   // Good
st2[0] += 2;                   // Good, string = "cbc"

🔨 🔥 Assignment 🔥 🔨

  1. Write a program that will ask the user for his/her surname, than using a while loop display each letter of the surname in separate lines. HINT 1 In a while condition check if a next character is different than NULL - end of string. HINT 2 Use additional int declared outside the while loop as the array iterator
  2. Modify the program, so it displays the ASCII codes of the given text.

<cstring> library contains some commonly used functions for text manipulation:

Function syntax Description
strlen(st1) Returns number of characters in string to null value (e.g. strlen(“abc”) → 3)
strcpy(st1, st2) Copy st2 to st1
strcat(st1, st2) Appends st2 at the end of st1
strcmp(st1, st2) Compares two texts, returns 0 if and only if the texts are the same
strncmp(st1, st2, n) Same as strcmp(), but compares only n first characters

🔨 🔥 Assignment 🔥 🔨

  1. Write a program that will ask the user for world wide web domain (eg. “google‌.‌com”) and concatenate it with “https‌://‌www.”. At the end resulting string has to be stored in a single array. HINT 1 Define array containing prefix with larger size: char address[100] = "https://www.";. HINT 2 Use strcat() to join both arrays.
  2. Display ASCII code of each address character in separate lines. Use a for loop with strlen() as stop condition to detect end of the string.
  3. Modify the for loop to display whole array, even after the NULL termination. What is contained within the array after the NULL sign?

More information on character sequences: http://www.cplusplus.com/doc/tutorial/ntcs/

<cstring> reference: http://www.cplusplus.com/reference/cstring/

Reading a line of text

To read a whole line of text (including spaces) it is possible to use std::cin.getline(st1, max_char) that reads line until the sign of the end of the line or when max_char are read.

char st1[100];
std::cin.getline(st1, 100);                                          // read up to 100 character and save them to st1

Sometimes, the std::cin.getline() function may capture information stored in the input buffer like the new line character. In order to avoid reading unwanted input and allow std::cin.getline() to capture the proper information we need to use std::cin.ignore(). This function should be used only when there is a problem with the result of std::cin.getline().

#include <limits>

//...

char st2[100];
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // ignore characters in the input buffer
std::cin.getline(st2, 100);                                         // read up to 100 character and save them to st2

Handling input with errors

Sometimes user, when asked for entering some value, may provide input of incompatible type. For example: user asked for age may write it using words instead of numbers. Such situations can be detected using std::cin.fail() method:

#include <iostream>
#include <limits>

int main()
{
    std::cout << "Enter an integer number: ";
    int number;

    while(true)
    {
        std::cin >> number;
        if(std::cin.fail())
        {
            std::cin.clear(); // Clears error state of the buffer
            std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // Ignores rest of the line
            std::cout << "You have entered wrong input" << std::endl;
        }else
        {
            break;
        }
    }
    std::cout << "The number is: " << number << std::endl;
    return 0;
}

Final assignments 🔥 🔨

The exercises should be placed in a while loop, so the user will be able to choose what he want to do or terminate the program by pressing x or X. Create a menu.

Exercise 1

  1. Ask the user to enter a piece of text. Read it, change every small letter to a capital letter and print the result on the screen.

Exercise 2

  1. Create and fill in an integer array with values provided by the user, or (for volunteers) random values from rand() function.
  2. Print created array.
  3. Find the minimal, maximal and mean value of the array. Print them.

Exercise 3

  1. Input a text line and show characters statistics (the number of occurrence for each character). HINT As a counter you can use a 256-element integer array, where the index is the ASCII value of the character.
  2. Sort the array. Use the bubble sort method, or (for volunteers) implement other type of sorting.

Homework 💥 🏠

  1. Create an array with 20 randomly sampled values from an interval 10.0 - 100.0 with a precision up to 1 decimal point, and then sort the array using insertion sort.
  2. Do a binary search to find a value in an array of 20 sorted values that is the closest to the one provided by the user.
  3. Create a program that will read a sentence from a user and then will print words in that sentence in a reverse order.

Exemplary input: > Alice has a cat

Program output: > cat a has Alice

  1. Read a text and then a word to find. Print the indices of occurrences of this word.

Exemplary input: > Alice has a cat. Alice has a dog.
> Alice

Program output: > 0 17

  1. Read a text from a user and then two words. Exchange the occurrences of the first words with a second word. Print the text after the change.

Exemplary input: > Alice has a cat
> Alice
> Bob

Program output: > Bob has a cat


Authors: Dominik Pieczyński, Tomasz Mańkowski